package com.woniuxy.qiniuyundemo.controller;


import com.woniuxy.qiniuyundemo.result.ResultInfo;
import com.woniuxy.qiniuyundemo.utils.QiniuCloudUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: linKe
 * @Date: 2021/11/23 16:01
 * @FileName: UploadController
 * @version: 1.0
 * @Description: 七牛云上传控制器
 */
@Log4j2
@RestController
@RequestMapping("/up")
public class UploadController {


    @PostMapping(value = "/uploadImg")
    public ResultInfo uploadImg(@RequestParam MultipartFile image, HttpServletRequest request) {
        ResultInfo result = new ResultInfo();
        if (image.isEmpty()) {
            result.setCode(400);
            result.setMsg("文件为空，请重新上传");
            return result;
        }

        try {
            byte[] bytes = image.getBytes();
            String imageName = UUID.randomUUID().toString();

            QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
            try {
                //使用base64方式上传到七牛云
                String url = qiniuUtil.put64image(bytes, imageName);
                //打印路径
                log.info(url);
                result.setCode(200);
                result.setMsg("文件上传成功");
                result.setInfo(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        } catch (IOException e) {
            result.setCode(500);
            result.setMsg("文件上传发生异常！");
            return result;
        }
    }

    @RequestMapping("/download")
    public ResultInfo downLoad(HttpServletRequest request, HttpServletResponse response,
                               @RequestParam("filename") String targetUrl
    ) {


        //获取downloadUrl
        String downloadUrl = "http://" + targetUrl;
        //本地保存路径
        String filePath = "D://temp//";

        String status = QiniuCloudUtil.download(downloadUrl, filePath);
        ResultInfo resultInfo = null;
        if ("200".equals(status)) {
            resultInfo = new ResultInfo(Integer.parseInt(status), "下载成功", null);
        } else {
            resultInfo = new ResultInfo(Integer.parseInt(status), "下载失败", null);
        }


        return resultInfo;

    }


}
